package com.download.database;

import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.support.annotation.NonNull;
import android.util.Log;

import com.liulishuo.filedownloader.util.FileDownloadHelper;
import com.waterstudio.filedownloader.ext.m3u8.BuildConfig;

/**
 * Created by chensuilun on 2019/3/13.
 */
@Database(entities = {TsTask.class}, version = 2)
public abstract class TsDatabase extends RoomDatabase {
    private static final String TAG = "TsDatabase";
    private static volatile TsDatabase INSTANCE;

    public abstract TsDao tsDao();

    public synchronized static TsDatabase getInstance() {
        if (INSTANCE == null) {
            synchronized (TsDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(FileDownloadHelper.getAppContext(),
                            TsDatabase.class, "filedownloader-m3u8.db")
                            .addMigrations(new Migration(1, 2) {
                                @Override
                                public void migrate(@NonNull SupportSQLiteDatabase database) {
                                    if (BuildConfig.DEBUG) {
                                        Log.i(TAG, "migrate 1=>2");
                                    }
                                    database.beginTransaction();
                                    try {
                                        database.execSQL(TsDao.V2_ADD_KEY);
                                        database.execSQL(TsDao.V2_ADD_IV);
                                        database.setTransactionSuccessful();
                                    } finally {
                                        database.endTransaction();
                                    }
                                }
                            })
                            .build();
                }
            }
        }
        return INSTANCE;
    }

    protected TsDatabase() {

    }

}
